<template>
  <JVxeTable
    ref="tableRef"
    stripe
    keepSource
    rowNumber
    asyncRemove
    dragSort
    :auto-resize="true" 
    :sync-resize="compData.activeKey"
    :maxHeight="700"
    :checkboxConfig="{range: true}"
    :disabledRows="{ fieldDesc: [true] }"
    :loading="compData.loading"
    :disabled="false"
    :columns="compData.columns"
    :dataSource="compData.dataSource"
    @valueChange="handleValueChange"
    @removed="handleRemove"
    @selectRowChange="handleSelectdRow"
  >
    <template #toolbarAfter>
      <a-button preIcon="ant-design:plus-outlined" type="primary" style="margin-right: 5px; margin-bottom: 8px;" 
        @click="handleSelectTemplateVar">
        选择变量
      </a-button> 
    </template>
  </JVxeTable>

  <MsgFieldSelectDrawer @register="registerMsgFieldDrawer" @select="handleReload" showFooter/>
</template>
<script lang="ts" setup>
import {onUnmounted, reactive, ref, useAttrs, watch} from 'vue';
import {useDrawer} from '/@/components/Drawer';
import MsgFieldSelectDrawer from '../../task/MsgFieldSelectDrawer.vue';
import {JVxeColumn} from '/@/components/jeecg/JVxeTable/types'
import {templateVarColumns} from '../template.data';
import {useGlobSetting} from '/@/hooks/setting';
import {useMessage} from '/@/hooks/web/useMessage';

// 声明Emits
const emit = defineEmits(['success', 'register', 'update:varData']);
const attrs = useAttrs()

const props = defineProps({
  taskId: { type: String },
  varData: { type: Array}
})
interface CompData {
  loading: boolean;
  columns: JVxeColumn[];
  activeKey: string;
  dataSource: Recordable[];
}

const compData = reactive<CompData>({
  loading: false,
  columns: templateVarColumns,
  activeKey: '',
  dataSource: []
})

const tableRef = ref()
const width = ref<number | string>('50%')
const { createMessage } = useMessage();
const glob = useGlobSetting();
const [registerMsgFieldDrawer, { openDrawer: openMsgFieldDrawer }] = useDrawer()
const [registerDrawer, { openDrawer }] = useDrawer()

onUnmounted(() => {
  console.log('template var component onUnmounted');
})

const getData = () => {
  const data = tableRef.value!.getTableData()
  return data
}

const handleValueChange = (event) => {
  console.log("handleValueChange, event: ", event)

  emit("update:varData", tableRef.value!.getTableData())
}

const validate = async (callback: Function) => {
  const values = tableRef.value!.getTableData()
  for(const item in values) {
    const errMap = await tableRef.value!.validateTable(values[item])
    if (errMap) {
      console.log('表单验证未通过：', { errMap });
      if (callback) {
        callback()
      }
      await tableRef.value!.validateTable()
      throw new Error(errMap);
    } 
  }
  return values
}


const handleRemove = async (event) => {
  try {
    let ids = []
    event.deleteRows.forEach(x => {
      if (!x.id.includes("row")) {
        ids.push(x.id)
      }
    })
    if (ids.length == 0) {
      return
    }
    console.log("delete ids: ", ids)
    await tableRef.value!.removeSelection();
    createMessage.success('删除成功！');
  } catch(e) {
    createMessage.warn('删除失败！');
  } finally {
    await tableRef.value!.removeSelection();
  }
}

const handleSelectdRow = (rows) => {
  console.log('rowsKey: ', rows.selectedRows);
}

watch(
  () => props.varData,
  (val : any) => {
    if (val && (!compData.dataSource || compData.dataSource.length == 0)) {
      compData.dataSource = val
    }
  }
);


const handleReload = (rows) => {
  compData.dataSource = tableRef.value!.getTableData()
  const map = new Map()
  rows.forEach(e => map.set(e.fieldName, e))

  const dataSourceMap = new Map()
  compData.dataSource.forEach(e => dataSourceMap.set(e.fieldName, e))

  compData.dataSource.forEach(e => {
    if (!map.has(e.fieldName)) {
      dataSourceMap.delete(e.fieldName)
    }
  })

  rows.forEach(e => {
    let fileData = dataSourceMap.get(e.fieldName) || {}
    fileData.key = e.fieldName
    fileData.desc = e.fieldDesc
    fileData.fieldName = e.fieldName
    dataSourceMap.set(e.fieldName, fileData)
  })

  compData.dataSource = Array.from(dataSourceMap.values())

  console.log(compData.dataSource);
  
  emit("update:varData", compData.dataSource)
}

const handleSelectTemplateVar = () => {
  openMsgFieldDrawer(true, {
    taskId: props.taskId
  })
}

defineExpose({getData, validate})
</script>
